/**
 * Author: Baoxu
 * Date:   12-7-3
 * Time:   上午8:41
 */


addLoadEvent(highlightPage);
addLoadEvent(navSlide);

//全局变量
var initObjectIndex;

//高亮导航条的当前页位置
function highlightPage(){
	var nav = document.getElementsByTagName("nav");
	var links = nav[0].getElementsByTagName("a");
	var pageURL = window.location.href;
	for(var i = 0 ; i < links.length ; i++){
		var link = links[i].getAttribute("href");
		if(pageURL.lastIndexOf(".") == -1){
			links[0].outerHTML = "<a class='here'>home</a>";
			return;
		}else if(pageURL.indexOf(link) != -1){
			var linkText = links[i].lastChild.nodeValue;
			initObjectIndex = getObjectIndex(links, this);
			initNavBg(initObjectIndex);
			//addClass(links[i],"here");
			links[i].outerHTML = "<a class='here'>" + linkText + "</a>";
			return;
		}
	}
}

//初始化导航条下背景的位置
function initNavBg(i){
	var slideBar = document.getElementById("nav-slide");
	slideBar.style.marginTop = "-5px";
	var toLeft = 125 + (i + 1) * 80;
	slideBar.style.marginLeft = toLeft + "px";
}

//移动导航条下背景
function navSlide(){
	var nav = document.getElementsByTagName("nav");
	var links = nav[0].getElementsByTagName("a");

	for(var i = 0 ; i < links.length ; i++){
		//暂时不会
		links[i].onmouseover = function(){
			var objectIndex = getObjectIndex(links, this);
			moveElement("nav-slide", (objectIndex + 1.8) * 70, -5, 10);
		}
	}

	nav[0].onmouseout = function(){
		initNavBg(initObjectIndex);
	}

}



//移动元素，给出目标元素，目的地坐标以及时间间隔
function moveElement(elementID, final_x, final_y, interval){
	var elem = document.getElementById("nav-slide");

	if(!parseInt(elem.style.marginLeft)){
		elem.style.marginLeft = "0px";
	}
	if(!parseInt(elem.style.marginTop)){
		elem.style.marginTop = final_y + "px";
	}

	var xpos = parseInt(elem.style.marginLeft);
	var ypos = parseInt(elem.style.marginTop);
	var dist = 0;

	if(elem.movement){
		clearTimeout(elem.movement);
	}
	if(xpos == final_x && ypos == final_y){
		return true;
	}
	if(xpos < final_x){
		dist = Math.ceil((final_x - xpos) / 10);
		xpos += dist;
	}
	if(ypos < final_y){
		dist = Math.ceil((final_y - ypos) / 10);
		ypos += dist;
	}
	if(xpos > final_x){
		dist = Math.ceil((xpos - final_x) / 10);
		xpos -= dist;
	}
	if(ypos > final_y){
		dist = Math.ceil((ypos - final_y) / 10);
		ypos -= dist;
	}

	elem.style.marginLeft = xpos + "px";
	elem.style.marginTop = ypos + "px";

	var repeat = "moveElement('" + elementID + "'," + final_x + "," + final_y + "," + interval + ")";
	elem.movement = setTimeout(repeat, interval);
}


//获取某对象元素在目标数组中的位置索引，如果有，返回索引，没有则返回-1
function getObjectIndex(targetArray, checkObject){
	for(var i = 0 ; i < targetArray.length ; i++){
		if(targetArray[i] == checkObject){
			return i;
		}
	}
	return -1;
}